<template>
	<view class="userInfoBox">
		<view class="box-hd" @click="login">
			<view class="box" v-if="islogin">
				<view class="avator">
					<image :src="userinfo.avatar" />
				</view>
				<view class="nickname">
					{{userinfo.nickname}}
				</view>
				<view class="phone-number" v-if='userinfo.userCardsQuantity!=0'>
					<template v-for="(item,index) in userinfo.userCards">
						<view :key="index" class="phone-number-cardtype" :style="{'backgroundColor':item.color}">
							{{item.name}} <text v-if="item.name=='五星专属'">:{{item.frequency}}次</text>
						</view>
					</template>
				</view>
			</view>
			<view class="box" v-else>
				<view class="avator">
					<image src="/static/logo.png" />
				</view>
				<view class="phone-number" style="color: red;">请先点我登录</view>
			</view>
		</view>

		<!-- 1是普通用户，2是教练 -->
		<view class="coach-entry" @click="noticeMore" v-if="userinfo.status==2">
			<image class="coach-entry-weightlifting" src="/static/me1.png" mode="widthFix"></image>
			<view class="coach-entry-text">
				<view class="coach-entry-title">
					教练工作台
				</view>
				<view class="coach-entry-desc">
					切换至教练模式，管理课程与学员
				</view>
			</view>
			<image class="coach-entry-arrow" src="/static/me3.png" mode="widthFix"></image>
		</view>

		<view class="booking-history">
			<view class="booking-title">
				约课记录
			</view>
			<view class="booking-Views">
				查看您所有的课程预约。
			</view>
			<view class="booking-list" v-for="(item, index) in recentBookings" :key="item.id">
				{{formatDateTime(item.startTime)}} {{item.courseName}} - {{getStatusText(item.status)}}
			</view>
			<view class="no-data" v-if="recentBookings.length === 0">
				暂无约课记录
			</view>
		</view>

		<view class="booking-history">
			<view class="booking-title">
				训练记录
			</view>
			<view class="booking-Views">
				追踪您的训练数据和进度。
			</view>
			<view class="booking-list" v-for="(item, index) in trainingReports" :key="item.id">
				<!-- {{formatDateTime(item.startTime)}} -->
				{{item.name}} - {{formatTrainingContent(item.trainingContent)}}
			</view>
			<view class="no-data" v-if="trainingReports.length === 0">
				暂无训练记录
			</view>
		</view>

		<view class="profile-section">
			<image src="/static/me2.png" mode="widthFix"></image>
			历史记录
		</view>
		<view class="history">
			<view class="history-item" @click="courseRecord">
				<text>
					我的约课记录
				</text>
				<u-icon name="arrow-right" color="#e0e0e0" size="16"></u-icon>
			</view>
			<view class="history-item" @click="trainingReportsListClick">
				<text>
					我的训练报告
				</text>
				<u-icon name="arrow-right" color="#e0e0e0" size="16"></u-icon>
			</view>
		</view>
		<!-- 
		<view class="profile-section">
			设置
		</view>
		<view class="set-item">
			账户与安全
		</view>
		<view class="set-item">
			通知设置
		</view>
		<view class="set-item">
			关于我们
		</view> -->

		<!-- 修改退出登录按钮，添加点击事件 -->
		<view class="logOut" @click="handleLogout">
			退出登录
		</view>
	</view>
</template>

<script>
	import {
		setUserInfo,
		getUserInfo,
		setToken,
		getToken,
		removeUserInfo,
		removeToken
	} from '@/utils/auth';
	export default {
		data() {
			return {
				userinfo: {},
				islogin: false,
				recentBookings: [], // 存储最近的约课记录
				trainingReports: [] // 存储训练报告
			}
		},
		onShow() {
			console.log(getUserInfo())
			if (getUserInfo() != undefined) {
				this.islogin = true
				// 已登录则获取预约记录和训练报告
				this.getRecentBookings()
				this.getTrainingReports() // 添加获取训练报告的调用
				this.wxuserget()
			}
			this.userinfo = getUserInfo() || {};
		},
		methods: {
			// 添加到methods部分
			handleLogout() {
				// 未登录状态下不显示退出确认
				if (!this.islogin) {
					uni.showToast({
						title: '您尚未登录',
						icon: 'none',
						duration: 2000
					});
					return;
				}

				// 显示确认对话框
				uni.showModal({
					title: '退出登录',
					content: '确定要退出登录吗？',
					confirmColor: '#FF6B6B',
					success: (res) => {
						if (res.confirm) {
							// 用户点击确定，执行退出登录操作
							console.log('用户确认退出登录');

							// 清除本地存储的用户信息和token
							removeUserInfo();
							removeToken();

							// 更新组件状态
							this.islogin = false;
							this.userinfo = {};
							this.recentBookings = [];
							this.trainingReports = [];

							// 显示退出成功提示
							uni.showToast({
								title: '已退出登录',
								icon: 'success',
								duration: 2000
							});

							// 如果需要，可以跳转到首页
							// uni.switchTab({
							//   url: '/pages/index/index'
							// });
						} else {
							// 用户点击取消，不做任何操作
							console.log('用户取消退出登录');
						}
					}
				});
			},
			wxuserget() {
				if (!getToken()) return; // 未登录不请求

				const data = {
					openid: getToken()
				};
				this.request('wxuserget', data, 'GET').then(res => {
					console.log("获取个人信息", res.data)
					setToken(res.data.openid)
					setUserInfo(res.data); //模拟存储用户信息
					this.userinfo = res.data;
				})
			},
			// 获取近期预约记录
			getRecentBookings() {
				if (!getToken()) return; // 未登录不请求

				const data = {
					openid: getToken()
				};

				this.request('gym/Booking/thisWeek', data, 'GET').then(res => {
					console.log("预约课程记录:", res);

					if (res && res.code === 200 && res.data) {
						// 将API返回的数据保存到recentBookings，最多显示3条
						this.recentBookings = res.data.slice(0, 3);
					} else {
						console.log('获取预约记录失败:', res?.msg);
						this.recentBookings = [];
					}
				}).catch(err => {
					console.error('请求发生错误:', err);
					this.recentBookings = [];
				});
			},

			// 获取训练报告
			getTrainingReports() {
				if (!getToken()) return; // 未登录不请求

				const data = {
					openid: getToken()
				};

				this.request('gym/TrainingReports/select', data, 'GET').then(res => {
					console.log("训练报告:", res);

					if (res && res.code === 200 && res.data) {
						// 将API返回的数据保存到trainingReports，最多显示3条
						this.trainingReports = res.data
					} else {
						console.log('获取训练报告失败:', res?.msg);
						this.trainingReports = [];
					}
				}).catch(err => {
					console.error('请求发生错误:', err);
					this.trainingReports = [];
				});
			},

			// 格式化训练内容显示
			formatTrainingContent(content) {
				// 如果内容太长，进行截断
				if (content && content.length > 20) {
					return content.substring(0, 20) + '...';
				}
				return content || '无训练内容';
			},

			// 格式化日期时间为 'YYYY-MM-DD HH:MM' 格式
			formatDateTime(dateTimeStr) {
				if (!dateTimeStr) return '';

				const date = new Date(dateTimeStr);
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0');
				const day = String(date.getDate()).padStart(2, '0');
				const hours = String(date.getHours()).padStart(2, '0');
				const minutes = String(date.getMinutes()).padStart(2, '0');

				return `${year}-${month}-${day} ${hours}:${minutes}`;
			},

			// 根据状态获取显示文本
			getStatusText(status) {
				const statusMap = {
					'booked': '已预约',
					'cancelled': '已取消',
					'pending': '待进行',
					'ongoing': '进行中',
					'completed': '已完成'
				};

				return statusMap[status] || status;
			},

			// 其他现有方法保持不变
			trainingReportsListClick() {
				if (!getToken()) {
					uni.showToast({
						title: '请先登录',
						icon: 'none'
					});
					return;
				}
				uni.navigateTo({
					url: '/pages/trainingReportsList'
				})
			},
			courseRecord() {
				if (!getToken()) {
					uni.showToast({
						title: '请先登录',
						icon: 'none'
					});
					return;
				}
				uni.navigateTo({
					url: '/pages/courseRecord'
				})
			},
			noticeMore() {
				if (!getToken()) {
					uni.showToast({
						title: '请先登录',
						icon: 'none'
					});
					return;
				}
				uni.navigateTo({
					url: '../me/mynotice/mynotice'
				})
			},
			login() {
				let that = this
				uni.login({
					provider: 'weixin',
					success: function(loginRes) {
						let form = {};
						form.code = loginRes.code; //用户code  注:用户的code每次登录都是随机的，所以不需要进行存储
						uni.showLoading({
							title: "登录中....",
							mask: true
						})
						console.log("form: ", form)
						that.request('wxlogin', form, 'POST').then(wxloginres => {
							console.log("wxloginres: ", wxloginres)
							if (wxloginres.code == 200) {
								uni.hideLoading()
								setTimeout(function() {
									uni.hideLoading();
								}, 2000);
								setToken(wxloginres.data.openid)
								setUserInfo(wxloginres.data); //模拟存储用户信息
								//成功后进入头像与昵称修改页面
								uni.navigateTo({
									url: '/pages/me/userinfo'
								})
							} else {
								uni.showToast({
									icon: "none",
									title: "登录失败，请稍后试试！",
									duration: 2000
								})
							}
						})
					},
					fail(err) {
						console.log(err)
					}
				});
			}
		}
	}
</script>

<style lang="scss">
	@import '@/common/mixins.scss';

	// @include rounded-box(32upx);
	// @include box-sizing-padding(24upx);
	// @include flex-center(center, space-between, column);
	.logOut {
		width: 640rpx;
		height: 120rpx;
		font-size: 32rpx;
		font-weight: bold;
		color: #FF6B6B;
		margin-top: 40rpx;
		@include rounded-box(20rpx, #1f1f1f);
		@include flex-center();
	}

	.set-item {
		width: 640rpx;
		height: 120rpx;
		font-size: 32rpx;
		color: #e0e0e0;
		margin-top: 25rpx;
		@include box-sizing-padding(24upx);
		@include rounded-box(20rpx, #1f1f1f);
		@include flex-center(center, left);
	}

	.history {
		width: 640rpx;
		height: 240rpx;
		margin: 25rpx 0 30rpx;
		@include rounded-box(20rpx, #1f1f1f);
		@include flex-center(center, space-between, column);

		.history-item {
			width: 100%;
			flex: 1;
			font-size: 32rpx;
			color: #e0e0e0;
			@include box-sizing-padding(24upx);
			@include flex-center(center, space-between);

			&:last-child {
				border-top: 1px solid #333;
			}

		}
	}

	.profile-section {
		width: 640rpx;
		height: 100rpx;
		color: #FFD700;
		font-size: 36rpx;
		font-weight: bold;
		border-bottom: 4rpx solid #FFD700;
		@include flex-center(center, left);

		image {
			width: 60rpx;
			margin-right: 15rpx;
		}
	}

	.booking-history {
		width: 640rpx;
		min-height: 300rpx;
		@include rounded-box(20rpx, #1f1f1f);
		@include box-sizing-padding(40rpx, 24rpx);
		@include flex-center(center, space-between, column);
		margin: 30rpx 0;

		.booking-title {
			width: 100%;
			color: #FFD700;
			font-size: 36rpx;
			font-weight: bold;
			border-bottom: 2rpx solid #333;
			padding: 30rpx 0;
		}

		.booking-Views {
			width: 100%;
			font-size: 30rpx;
			color: #e0e0e0;
			margin: 40rpx 0;
		}

		.booking-list {
			width: 100%;
			border-bottom: 1px dashed #444;
			padding: 22rpx 0;
			color: #e0e0e0;

			&:last-child {
				border-bottom: none;
			}
		}
	}

	.coach-entry {
		width: 640rpx;
		height: 200rpx;
		@include rounded-box(20rpx, #1f1f1f);
		@include box-sizing-padding(40rpx, 24rpx);
		@include flex-center(center, space-between);

		.coach-entry-weightlifting {
			width: 60rpx;
			margin-right: 20rpx;
		}

		.coach-entry-text {
			flex: 1;
			height: 100%;
			@include flex-center(center, center, column);

			.coach-entry-title {
				width: 100%;
				font-size: 34rpx;
				font-weight: bold;
				color: #FFD700;
				margin-bottom: 20rpx;
			}

			.coach-entry-desc {
				width: 100%;
				font-size: 28rpx;
				color: #aaa;
			}
		}

		.coach-entry-arrow {
			width: 40rpx;
			margin-left: 20rpx
		}
	}

	.userInfoBox {
		@include flex-center(center, space-between, column);

	}

	.box-hd {
		width: 680rpx;
		height: 400rpx;
		margin: 30rpx auto;
		@include rounded-box(20rpx, #FFD700);
		@include flex-center();

		.box {
			width: 680rpx;
			height: 400rpx;
			@include flex-center(center, center, column);
		}

		.avator {
			width: 160rpx;
			height: 160rpx;
			background: #fff;
			border: 5rpx solid #f1f1f1;
			border-radius: 50%;
			margin: 0 auto;
			overflow: hidden;

			image {
				width: 160rpx;
				height: 160rpx;
			}
		}

		.nickname {
			width: 680rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			margin-top: 15rpx;
			font-size: 30rpx;
			font-weight: bold;
			color: #fff;
		}

		.phone-number {
			width: 680rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			margin-top: 20rpx;

			.phone-number-cardtype {
				font-size: 24rpx;
				width: 180rpx;
				height: 50rpx;
				color: #fff;
				border-radius: 10rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				margin-left: 10rpx;
			}
		}
	}

	/* 添加无数据样式 */
	.no-data {
		width: 100%;
		padding: 20rpx 0;
		text-align: center;
		color: #777;
		font-size: 28rpx;
	}
</style>